<?
session_start();

include('./../config/db_settings.php');
include('pms_inc.php');

// chinese input:
 if(empty($_SESSION[$settings['session_prefix'].'cn_input']))
 {
  $cn_input = 0;
  
  // $cn_input 0: off; 1: pinyin; 2: wubi
  if($cn_input>2) $cn_input = 0;
  if($cn_input<0) $cn_input = 0;

  $_SESSION[$settings['session_prefix'].'cn_input'] = $cn_input;
 }else
 {
	$cn_input = intval($_SESSION[$settings['session_prefix'].'cn_input']);
 }

$user = $_SESSION[$settings['session_prefix'].'user_id'];
$username  = $_SESSION[$settings['session_prefix'].'user_name'];
//echo '$username:'.$username;

?>
<html>
<head>
<title>Private Message Center</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css"
	href="../templates/<? echo $settings['template'] ?>/style_lp.css"
	media="all" />
<script src="../js/google.js" type="text/javascript"></script>
<script src="../js/textLength.js" type="text/javascript"></script>
<script src="../js/javascripts.js" type="text/javascript"></script>
<script src="../js/verifyPMUsers.js" type="text/javascript"></script>
<?
if($cn_input == 1)
{
?>
<script src="../js/ime_data.js" type="text/javascript"></script>
<?
}
?>

<?
if($cn_input == 2)
{
?>
<script src="../js/ime_wubi_data.js" type="text/javascript"></script>
<?
}
?>

<?
if($cn_input > 0)
{
?>
<script src="../js/ime.js" type="text/javascript"></script>
<?
}
?>
<script type="text/javascript">
	function verify_postingform(name_error,subject_error,text_error)
	 {
		var names = document.forms['postingform'].elements['name'].value;
		 {
			if(is_postingform_complete(name_error,subject_error,text_error)){
				return true;
			}else{
				return false;
			}
		 }
	 }
</script>
</head>
<body>
<?
//Are they logged in or not?
if(!$user)
{
	echo "<br><p>You aren't logged in. Please log in first.</p><br>";
}

else
{
	//check variable(s) from the URL first
	//$msg_id = $_REQUEST['msg_id'];
	$msg_id = isset($_REQUEST['msg_id']) ? $_REQUEST['msg_id']:"";
	$user_id = isset($_REQUEST['uid']) ? $_REQUEST['uid'] : "";
	$msg_multi_id = isset($_REQUEST['msg_multi_id']) ? $_REQUEST['msg_multi_id'] : "";

	$receiver_id = 0;
	$sendto = "";
	$subject = "";

	if($msg_id>0)
	{
		//Get all of the information about the message with and id number of the one sent through the URL
		$view_msg = mysql_query("SELECT a.receiver_id, a.multi_id, a.subject, b.user_name sendto FROM ".$db_settings['messages_table']." a join ".$db_settings['userdata_table']." b on a.sender_id=b.user_id WHERE a.id = '$msg_id'");
		$msg = mysql_fetch_array($view_msg);

		$receiver_id = $msg['receiver_id'];
		$multi_id = $msg['multi_id'];

		//make sure this msg was sent to the current user
		if($receiver_id == $user)
		{
			$subject = "RE: ".htmlspecialchars(stripslashes(base64_decode($msg['subject'])));
			if(empty($msg_multi_id))
			{
				$sendto = $msg['sendto'];
			}
			else
			{
				// get the sendto for reply all
				if($multi_id == 0)
				{
					$sendto = $msg['sendto'];
				}
				else
				{
					$replyall_sql = mysql_query("SELECT sentfrom, sentto FROM ".$db_settings['messages_multi_table']." WHERE multi_id = '$multi_id'");
					$replyall = mysql_fetch_array($replyall_sql);

					$sentfrom = $replyall['sentfrom'];
					$senttolist = $replyall['sentto'];
					
					$sendto = $sentfrom;
					
					$senttousers = split(";", $senttolist);
					foreach($senttousers as $senttouser){
						$senttouser = trim($senttouser);
						if(strlen($senttouser)>0){
							if(strtolower($senttouser) != strtolower($username))
							{
								$sendto = $sendto.";".$senttouser;
							}
						}
					}
					
				}
			}
		}

	}
	else
	{
		if($user_id>0)
		{
			//Get the send-to user name
			$sql = mysql_query("SELECT user_name sendto FROM ".$db_settings['userdata_table']." where user_id = '$user_id'");
			$row = mysql_fetch_array($sql);
			$sendto = $row['sendto'];
		}

	}


	//Get your private message count
	$sql = mysql_query ("SELECT count(*) pm_count FROM ".$db_settings['messages_table']." WHERE sender_id='$user' and received in (0,1,4,5)");
	$row = mysql_fetch_array ($sql);
	$pm_count = $row['pm_count'];

	$percent = $pm_count/$limit;
	$percent = $percent * '100';

	$sql = mysql_query ("SELECT count(*) new_count FROM ".$db_settings['messages_table']." WHERE receiver_id='$user' and (received = 0 or received =2)");
	$row = mysql_fetch_array ($sql);
	$totalNew = $row['new_count'];
	?>
<br>
<center><b><a href="inbox.php">收件箱 </a> | <a href="compose.php">Compose</a>
| <a href="sent.php">发件箱</a></b><br />
<b> 发件箱: <? echo "$pm_count"." of "."$limit"." Total  |  "."$percent"."% full"; ?></b><br />
</center>

<br>
<?php
if(!empty($totalNew)){
 ?>
<div style="padding: 0px 0px 0px 10px;color:red;">		
<p>You have <? echo $totalNew;?> new incoming message(s).</p>
</div>
 <?php
}
 ?>
<div id="form" style="padding: 0px 0px 10px 10px;"><?
$message ="";
if($pm_count>=$limit){
	$error = 'Your sentbox is full. Please delete some old messages from the sentbox.';
}else{
	if($sendto)
	{
		//go directly to the form
		$receiver = $sendto;
		$error = '0';
	}
	else
	{
		//So here we get the variable submitted through the form to this page
		$receiver = trim($_POST['name']);
		$subject = trim($_POST['subject']);
		$message = trim($_POST['text']);
		$error = '0';

		//If they are all blank we just say to compose a message
		if(!$receiver AND !$subject)
		{
			?>
<div style="float: left;"></div>
<div style="font-weight: bold; float: left;">Please compose a
message.&nbsp;</div>
<div style="font-weight: bold; color: red; float: left;">Now you can
send a PM to multiple users. Please use semicolon(;) to separate user
names.</div>
<div style="clear: both;"></div>
			<?
		}

		//Since this form was partially filled out we need to return an error message
		else
		{
			if (!$receiver)
			{
				$error = 'You must enter a receiver to your message';
			}

			if (!$subject)
			{
				$error = 'You must enter a subject';
			}

			//huofu modify: user name may include &
			//if(strpos($receiver, "&") !== false){
			//	$error = "User name can not contain '&'.";
			//}

			//If the variable error is not set to zero, we have a problem and should show the error message
			if($error != '0')
			{
				// we display the error later
			}

			//There are no errors so far which means the form is completely filled out
			else
			{
				// if the first char or the last char of $receiver is ';'
				if(substr($receiver,0,1)==';'){
					$receiver = substr($receiver,1);
				}
				if(substr($receiver,strlen($receiver)-1)==';'){
					$receiver = substr($receiver,0,strlen($receiver)-1);
				}

				//now let's check if the receiver has multi user names
				if(strpos($receiver, ";") !== false){
					$users = split(";",$receiver);
					$total = $pm_count + count($users);
					if($total > $limit)
					{
						$more = $total - $limit;
						$error = "You do not have enough space in your Sentbox to send this PM. You need ".$more." more space.";
					}else
					{
						// multi receivers mode
						// check again if every username is valid
						foreach($users as $senttouser){
							$senttouser = trim($senttouser);
							if(strlen($senttouser)>0){
								$sql = mysql_query ("SELECT count(*) user_count FROM ".$db_settings['userdata_table']." WHERE lower(user_name) = '".mysql_real_escape_string(strtolower($senttouser))."'");
								$row = mysql_fetch_array ($sql);
								$user_count = $row['user_count'];
								if($user_count==0){
									$error = $error."<b>".$senttouser."</b>    is not a valid user name.<br/>";
								}
							}
						}

						if($error != '0')
						{
							// we display the error later
						}else
						{
							//There might already be a sessioned time variable, if so we need to get it for the flood check
							$time = $_SESSION['pm_time'];

							//If there is a time variable already, set it to the varialbe $old_time
							if($time > '0')
							{
								$old_time = $time;
							}

							//Here we get the minutes and seconds on the server time using the date function, and set that to the $time variable
							//Now we find the difference between this time ($time) and the time that the page was submitted ($old_time)
							$time = date('ymdHis');
							$difference = $time - $old_time;

							//If the two times have a difference greater or equal to 10, which is 10 seconds, they can submit the message, this is for flood protection
							if($difference >= '10')
							{
								$x_subject=base64_encode($subject);
								$x_message=base64_encode($message);
								
								mysql_query("INSERT INTO ".$db_settings['messages_multi_table']." (sentfrom, sentto) VALUES('$username', '$receiver')") or die (mysql_error());
								$multi_id =  mysql_insert_id();
								if($multi_id == 0)
								{
									echo "There was a database error. The message wasn't sent successfully.";
									exit;
								}
								
								//send the pm to each user
								foreach($users as $senttouser)
								{
									$senttouser = trim($senttouser);
									if(strlen($senttouser)>0){
										//Are they trying to send a message to a real user or to something they just made up?
										$user_check = mysql_query("SELECT user_id FROM ".$db_settings['userdata_table']." WHERE user_name='$senttouser'");
										$row = mysql_fetch_array ($user_check);
										$receiver_id = $row['user_id'];
										$user_check = $receiver_id;

										//The user is real and not made up if this is true
										if($user_check > '0')
										{
											//Get their private message count
											//$sql = mysql_query ("SELECT count(*) receiver_pm_count FROM ".$db_settings['messages_table']." WHERE receiver_id='$receiver_id' and received<4");
											//$row = mysql_fetch_array ($sql);
											//$receiver_pm_count = (int)$row['receiver_pm_count'];

											//You cant have more than limited private messages, if they try sending a message to a user with a full inbox return an error message
									//		if($receiver_pm_count >= $limit)
									//		{
									//			$error = $error." Sorry, <b>".$senttouser."</b>'s inbox is full. The message can not be delivered to this user.<br/>";
									//		}
											//huofu: change logic here, instead of check receiver's inbox, we now check sender's
											//Get your private message count
											$sql = mysql_query ("SELECT count(*) pm_count FROM ".$db_settings['messages_table']." WHERE sender_id='$user' and received in (0,1,4,5)");
											$row = mysql_fetch_array ($sql);
											$sender_pm_count = $row['pm_count'];
											if($sender_pm_count >= $limit)
											{
												$error = 'Sorry, your inbox is full. The message can not be delivered.';
											}
							
											else
											{
												//And now we stick the message in the database with all the correct information
												mysql_query("INSERT INTO ".$db_settings['messages_table']." (receiver_id, sender_id, subject, message, multi_id) VALUES($receiver_id, $user, '$x_subject', '$x_message', $multi_id)") or die (mysql_error());
											}
										}else
										{
											$error = $error.' <b>'.$senttouser.'</b> is not a valid username. The message can not be delivered to this user<br/>';
										}
									}
								}
								if($error == '0')
								{
									//Let the user know everything went ok.
									echo "<p><b>You have successfully sent a private message to all of the receivers!</b></p><br>";
									$subject='';
									$message='';
								}else
								{
									$error = '<b>The message was not successfully sent to all of the receivers. Here is a list of the errors:</b><br/>'.$error;
								}

								$_SESSION['pm_time'] = $time;
							}

							//Since they are trying to send messages faster than every 10 seconds, give them an error message
							else
							{
								$error = 'You must wait 10 seconds before sending another private message';
							}
						}
					}
				}else
				{
					// one receiver only mode
					//Are they trying to send a message to a real user or to something they just made up?
					$user_check = mysql_query("SELECT user_id FROM ".$db_settings['userdata_table']." WHERE user_name='$receiver'");
					$row = mysql_fetch_array ($user_check);
					$receiver_id = $row['user_id'];
					$user_check = $receiver_id;

					//The user is real and not made up if this is true
					if($user_check > '0')
					{
						//There might already be a sessioned time variable, if so we need to get it for the flood check
						$time = isset($_SESSION['pm_time']) ? $_SESSION['pm_time'] : "";
						$old_time = $time;
						//If there is a time variable already, set it to the varialbe $old_time
						if($time > '0')
						{
							$old_time = $time;
						}

						//Here we get the minutes and seconds on the server time using the date function, and set that to the $time variable
						//Now we find the difference between this time ($time) and the time that the page was submitted ($old_time)
						$time = date('ymdHis');
						$difference = $time - $old_time;

						$_SESSION['pm_time'] = $time;

						//If the two times have a difference greater or equal to 10, which is 10 seconds, they can submit the message, this is for flood protection
						if($difference >= '10')
						{
							//Get their private message count
							//$sql = mysql_query ("SELECT count(*) receiver_pm_count FROM ".$db_settings['messages_table']." WHERE receiver_id='$receiver_id' and received<4");
							//$row = mysql_fetch_array ($sql);
							//$receiver_pm_count = (int)$row['receiver_pm_count'];

							//You cant have more than limited private messages, if they try sending a message to a user with a full inbox return an error message
							//if($receiver_pm_count >= $limit)
							//{
							//	$error = 'Sorry, the receiver\'s inbox is full. The message can not be delivered.';
							//}

							//huofu: change logic here, instead of check receiver's inbox, we now check sender's
							//Get your private message count
							$sql = mysql_query ("SELECT count(*) pm_count FROM ".$db_settings['messages_table']." WHERE sender_id='$user' and received in (0,1,4,5)");
							$row = mysql_fetch_array ($sql);
							$sender_pm_count = $row['pm_count'];
							if($sender_pm_count >= $limit)
							{
								$error = 'Sorry, your inbox is full. The message can not be delivered.';
							}
							
							
							else
							{
								//And now we stick the message in the database with all the correct information
								$x_subject=base64_encode($subject);
								$x_message=base64_encode($message);
								mysql_query("INSERT INTO ".$db_settings['messages_table']." (receiver_id, sender_id, subject, message) VALUES($receiver_id, $user, '$x_subject', '$x_message')") or die (mysql_error());
								$subject = "";
								//Let the user know everything went ok.
								echo "<p><b>You have successfully sent a private message!</b></p><br>";
								if($pm_count == $limit-1){$error="   ";}
								$subject = '';
								$message = '';
							}
						}
						//Since they are trying to send messages faster than every 10 seconds, give them an error message
						else
						{
							$error = 'You must wait 10 seconds before sending another private message';
						}
					}

					//If they mis spelled or, made up a username, then give an error message telling them its wrong.
					else
					{
						$error = 'That username does not exist, please try again.';
					}
				}
			}
		}
	}
}

//Since we may have set the error variable to something while trying to send the messae, we need another error check
if($error != '0')
{
	echo "<b><p>&nbsp;&nbsp;$error</p></b><br/>";
}

//else
//{
//Here's the form for the input
?>
<div id="divMsg" style="padding: 0px 0px 10px 10px; color: red;"></div>
<form method="post" action="compose.php" id="postingform"
	accept-charset="UTF-8">

<table width="80%">
	<tr>
		<td></td>
		<td colspan="2" align="left"><?
		if($cn_input > 0)
		{
		?><INPUT name="EnglishMode" 
			ID="EnglishMode" onclick="changeinputmode();" type="checkbox"
			checked="yes" OnFocus="IME.InputArea.focus()">关闭在线中文输入(Ctrl) <INPUT 
			name="FullShape" ID="FullShape" type="checkbox" 
			OnFocus="IME.InputArea.focus()">全形字符(F12) <INPUT name="AutoUp" 
			ID="AutoUp" type="checkbox" OnFocus="IME.InputArea.focus()">自动上字(F2)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;翻页PageUp/PageDown<?
		}
		?></td> 
	</tr>
	<tr>
		<td width="150px" align="left" valign="top">
		<p>&nbsp;Username</p>
		</td>
		<td width="800px" align="left" valign="top"><input <?
		if($cn_input > 0)
		{
		?>OnFocus="LoadIME(this.id);" OnKeyDown="return ImeKeyDown(event)"
			OnKeyPress="return ImeKeyPress(event)"
			OnKeyUp="return ImeKeyUp(event)" <?
		}
		?> name="name" type="text" id="name" tabindex=4 
			size="68" value="<? echo "$receiver"; ?>" />&nbsp;<input
			type="button" value="Verify Username" onclick="verifyUsers();" tabindex=5/> <img
			id="throbber-verify" style="visibility: hidden;"
			src="../templates/default/images/throbber_submit.gif" alt=""
			width="16" height="16" /></td>
		<td width="200px"><?
		if($cn_input > 0)
		{
		?><INPUT OnFocus="IME.InputArea.focus();" Name="Comp"
			ID="Comp" readonly="readonly" Size="19" style="visibility: hidden;"
			style="FONT-SIZE: 12pt; FONT-FAMILY: simsun, arial; font-weight: bold"><?
		}
		?></td>
	</tr>

	<tr>
		<td width="150px" align="left" valign="top">
		<p>&nbsp;Subject</p>
		</td>
		<td width="" align="left" valign="top"><textarea id="subject" rows=3 tabindex=6
			cols="70" wrap="virtual" name="subject" length="200" <?
		if($cn_input > 0)
		{
		?> OnFocus="LoadIME(this.id);" OnKeyDown="return ImeKeyDown(event)"
			OnKeyPress="return ImeKeyPress(event)"
			OnKeyUp="return ImeKeyUp(event)"<?
		}
		?>  ><? echo "$subject"; ?></textarea></td>
		<td rowspan="7"><?
		if($cn_input > 0)
		{
		?><TEXTAREA OnFocus="IME.InputArea.focus();" Name="Cand"
			ID="Cand" readonly="readonly" Rows="15" Cols="20" style="visibility: hidden;"
			style="FONT-SIZE: 12pt; FONT-FAMILY: simsun, arial"></TEXTAREA><?
		}
		?></td>
	</tr>
	<tr>
		<td width="150px" align="left" valign="top">&nbsp;</td>
		<td width="" align="left" valign="top"><span class="xsmall">Subject's
		max length is 200 characters. You have <font color="red"><span
			id="subjectsize"></span></font>&nbsp;characters left.</span></td>

	</tr>
	<tr>
		<td width="150px" align="left" valign="top">&nbsp;</td>
		<td width="" align="left" valign="top">&nbsp;</td>

	</tr>
	<tr>
		<td width="150px" align="left" valign="top">
		<p>&nbsp;Message Body</p>
		</td>
		<td width="" align="left" valign="top"><textarea name="text" tabindex=7 
			type="text" id="text" value="" cols="70" rows="12" length="1500" <?
		if($cn_input > 0)
		{
		?>
			OnFocus="LoadIME(this.id);" OnKeyDown="return ImeKeyDown(event)"
			OnKeyPress="return ImeKeyPress(event)"
			OnKeyUp="return ImeKeyUp(event)"<?
		}
		?> ><? echo "$message"; ?></textarea></td>

	</tr>
	<tr>
		<td width="150px" align="left" valign="top">&nbsp;</td>
		<td width="" align="left" valign="top"><span class="xsmall">Message
		body's max length is 1500 characters. You have <font color="red"><span
			id="textsize"></span></font>&nbsp;characters left.</span></td>

	</tr>
	<tr>
		<td width="150px" align="left" valign="top">&nbsp;</td>
		<td width="" align="left" valign="top">&nbsp;</td>

	</tr>

	<tr>
		<td>&nbsp;</td>
		<td><input type="submit" name="Submit" value="Send Message" tabindex=8 
			onclick="return verify_postingform('No%20username%20has%20been%20entered','No%20subject%20has%20been%20entered','');" />
		<img id="throbber-submit" style="visibility: hidden;"
			src="../templates/default/images/throbber_submit.gif" alt=""
			width="16" height="16" /></td>

	</tr>
</table>
</form>
</div>
<?
//}
}
?>
<script type="text/javascript">
	document.getElementById("subjectsize").innerHTML = 200 - document.getElementById("subject").value.len();
	document.getElementById("textsize").innerHTML = 1500 - document.getElementById("text").value.len();
</script>
</body>
</html>
